<template>
  <table-manage>
    <template #search>
      <el-form-item label="学生姓名">
        <el-input placeholder="请输入学生姓名" v-model="pageParam.searchObject.roleName"/>
      </el-form-item>
      <el-form-item label="学号">
        <el-input placeholder="请输入学号" v-model="pageParam.searchObject.roleKey"/>
      </el-form-item>
      <el-form-item label="考试类型">
        <el-select v-model="examType" placeholder="请选择考试类型">
          <el-option label="期中考试" value="midterm"/>
          <el-option label="期末考试" value="final"/>
          <el-option label="月考" value="monthly"/>
          <el-option label="模拟考" value="mock"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadTableData" :icon="Search">搜索</el-button>
        <el-button @click="onResetSearchForm" :icon="Refresh">重置</el-button>
      </el-form-item>
    </template>

    <template #operate>
      <el-button type="primary" @click="onCreate" :icon="Plus">录入成绩</el-button>
      <el-button type="success" @click="exportGrades" :icon="Download">导出成绩</el-button>
      <el-button plain type="danger" @click="onDeleteBatch" :icon="DeleteFilled">批量删除</el-button>
    </template>

    <template #default>
      <el-table v-loading="loading" :data="pageVo.records" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="roleName" label="学生姓名" width="120"/>
        <el-table-column prop="roleKey" label="学号" width="150"/>
        <el-table-column prop="className" label="班级" width="120"/>
        <el-table-column label="各科成绩" min-width="400">
          <el-table-column prop="chinese" label="语文" width="100" sortable/>
          <el-table-column prop="math" label="数学" width="100" sortable/>
          <el-table-column prop="english" label="英语" width="100" sortable/>
          <el-table-column prop="total" label="总分" width="100" sortable/>
        </el-table-column>
        <el-table-column prop="rank" label="排名" width="100" sortable/>
        <el-table-column prop="examTime" label="考试时间" width="180"/>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="onEdit(scope.row)" :icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(scope.row)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #page>
      <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                     :total="pageVo.total"
                     v-model:page-count="pageVo.pageNo"
                     v-model:page-size="pageParam.pageSize"
                     :page-sizes=[10,20,50,100]
      />
    </template>

    <template #form>
      <el-dialog v-model="dialogEditVisible" :title="editForm.id ? '编辑成绩' : '录入成绩'" width="600px">
        <el-form ref="sstFormRef" :model="editForm" :rules="rules" label-width="100px">
          <el-form-item prop="roleName" label="学生姓名">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item prop="roleKey" label="学号">
            <el-input v-model="editForm.roleKey"></el-input>
          </el-form-item>
          <el-form-item prop="className" label="班级">
            <el-select v-model="editForm.className" placeholder="请选择班级">
              <el-option label="高一(1)班" value="高一(1)班"/>
              <el-option label="高一(2)班" value="高一(2)班"/>
              <el-option label="高二(1)班" value="高二(1)班"/>
              <el-option label="高二(2)班" value="高二(2)班"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="examType" label="考试类型">
            <el-select v-model="editForm.examType" placeholder="请选择考试类型">
              <el-option label="期中考试" value="midterm"/>
              <el-option label="期末考试" value="final"/>
              <el-option label="月考" value="monthly"/>
              <el-option label="模拟考" value="mock"/>
            </el-select>
          </el-form-item>
          <el-form-item label="考试成绩">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item prop="chinese" label="语文">
                  <el-input-number v-model="editForm.chinese" :min="0" :max="150"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="math" label="数学">
                  <el-input-number v-model="editForm.math" :min="0" :max="150"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="english" label="英语">
                  <el-input-number v-model="editForm.english" :min="0" :max="150"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item prop="examTime" label="考试时间">
            <el-date-picker v-model="editForm.examTime" type="datetime" placeholder="选择考试时间"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogEditVisible = false">取消</el-button>
            <el-button type="primary" @click="onUpdateFormConfirm(sstFormRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </template>
  </table-manage>
</template>

<script setup lang="ts">
import {onMounted, nextTick, reactive, ref, computed} from "vue";
import {reqCommonFeedback, reqSuccessFeedback} from "@/api/ApiFeedback";
import roleApi, {grantPermissionsByRoleId} from "@/api/system/sys-role-api";
import TableManage from "@/components/container/TableManage.vue";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import {DeleteFilled, Plus, Refresh, Search, Edit, Delete, Download} from "@element-plus/icons-vue";

const multipleSelection = ref<any[]>([]);
const examType = ref('');
const dialogEditVisible = ref<boolean>(false);
const sstFormRef = ref<FormInstance>();

// 表单参数
const editForm = ref({
  id: '',
  roleName: '',
  roleKey: '',
  className: '',
  examType: '',
  chinese: 0,
  math: 0,
  english: 0,
  examTime: '',
  total: computed(() => {
    return (editForm.value.chinese || 0) + (editForm.value.math || 0) + (editForm.value.english || 0);
  })
});

// 分页参数
const pageParam = ref<PageParam>({pageNo: 1, pageSize: 20, searchObject: {}});
// api返回的分页数据
const pageVo = ref<PageVO>({pageNo: 1, pageSize: 20, total: 0, records: []});
// 加载进度
const loading = ref<boolean>(true);

// 表单校验规则
const rules = reactive({
  roleName: [{required: true, message: '请输入学生姓名', trigger: 'blur'}],
  roleKey: [{required: true, message: '请输入学号', trigger: 'blur'}],
  className: [{required: true, message: '请选择班级', trigger: 'change'}],
  examType: [{required: true, message: '请选择考试类型', trigger: 'change'}],
  chinese: [{required: true, type: 'number', message: '请输入语文成绩', trigger: 'blur'}],
  math: [{required: true, type: 'number', message: '请输入数学成绩', trigger: 'blur'}],
  english: [{required: true, type: 'number', message: '请输入英语成绩', trigger: 'blur'}],
  examTime: [{required: true, message: '请选择考试时间', trigger: 'change'}]
});

// 初始化数据
onMounted(() => {
  loadTableData();
});

const loadTableData = () => {
  if (!loading.value) loading.value = true;
  let param = {
    pageNo: pageParam.value.pageNo,
    pageSize: pageParam.value.pageSize,
    sysRole: {
      roleName: pageParam.value.searchObject.roleName,
      roleKey: pageParam.value.searchObject.roleKey,
      examType: examType.value
    }
  };
  reqCommonFeedback(roleApi.listByPage(param), (data: any) => {
    pageVo.value = data;
    loading.value = false;
  });
}

const onUpdateFormConfirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      if (!editForm.value.id) {
        // 新增
        reqSuccessFeedback(roleApi.add(editForm.value), '成绩录入成功', () => {
          loadTableData();
          dialogEditVisible.value = false;
          // 更新班级统计信息
          updateClassStatistics(editForm.value.className);
        });
      } else {
        // 修改
        reqSuccessFeedback(roleApi.update(editForm.value), '成绩修改成功', () => {
          loadTableData();
          dialogEditVisible.value = false;
          // 更新班级统计信息
          updateClassStatistics(editForm.value.className);
        });
      }
    }
  });
}

// 添加更新班级统计信息的方法
const updateClassStatistics = (className: string) => {
  // 调用后端API更新班级统计信息
  reqCommonFeedback(roleApi.updateClassStatistics(className), () => {
    ElMessage.success('班级统计信息已更新');
  });
}

const onEdit = (row: any) => {
  editForm.value = {...row};
  dialogEditVisible.value = true;
}

const onDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该成绩记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    reqSuccessFeedback(roleApi.deleteBatch([row.id]), '删除成功', () => {
      loadTableData();
    });
  });
}

const exportGrades = () => {
  ElMessage.success('成绩导出功能开发中...');
}

const onResetSearchForm = () => {
  pageParam.value.searchObject = {};
  examType.value = '';
}

const onCreate = () => {
  editForm.value = {
    id: '',
    roleName: '',
    roleKey: '',
    className: '',
    examType: '',
    chinese: 0,
    math: 0,
    english: 0,
    examTime: '',
    total: computed(() => {
      return (editForm.value.chinese || 0) + (editForm.value.math || 0) + (editForm.value.english || 0);
    })
  };
  dialogEditVisible.value = true;
}

const onDeleteBatch = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的成绩记录');
    return;
  }
  let ids: string[] = multipleSelection.value.map(item => item.id);
  ElMessageBox.confirm('确认批量删除所选成绩记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    reqCommonFeedback(roleApi.deleteBatch(ids), () => {
      ElMessage({type: 'success', message: '删除成功'});
      loadTableData();
    });
  });
}

const handleSelectionChange = (arr: any) => {
  multipleSelection.value = arr;
}
</script>

<style scoped>
.el-input-number {
  width: 100%;
}
</style>